<template>
  <div class="container">
    <h2>Raccoon Guide</h2>
    <h3>Login</h3>
    <!-- Login form -->
    <form @submit.prevent="handleLogin">
      <div class="form-group">
        <label for="userName">userName</label>
        <input
          type="text"
          id="userName"
          v-model="userName"
          required
          placeholder="Enter your userName"
        />
      </div>
      <div class="form-group">
        <label for="password">Password</label>
        <input
          type="password"
          id="password"
          v-model="password"
          required
          placeholder="Enter your password"
        />
      </div>
      <button type="submit">Login</button>
    </form>
    <p>
      Don't have an account?
      <router-link to="/register">Register here</router-link>
    </p>
  </div>
</template>

<script lang="ts">
import { ref } from 'vue';

export default {
  name: 'LoginPage',
  setup() {
    const userName = ref('');
    const password = ref('');

    const handleLogin = async () => {
      try {
        const response = await fetch('http://localhost:7777/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            userName: userName.value,
            password: password.value,
          }),
        });

        const data = await response.json();

        if (response.ok) {
          localStorage.setItem('token', data.data.token);

          // Store user info as well if needed
          localStorage.setItem('userId', data.data.id);
          localStorage.setItem('userName', data.data.userName);

          // Redirect to the homepage or any other route
          window.location.href = '/'; 
        } else {
          alert(data.message || 'Login failed');
        }
      } catch (error) {
        console.error('Login failed:', error);
        alert('An error occurred. Please try again.');
      }
    };

    return {
      userName,
      password,
      handleLogin,
    };
  },
};
</script>

<style scoped>
.container {
  width: 300px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #fafafa;
}

h2 {
  margin-bottom: 10px;
  color: #4CAF50;
}

h3 {
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

input {
  width: 100%;
  padding: 10px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  width: 100%;
}

button:hover {
  background-color: #45a049;
}

p {
  margin-top: 20px;
}

p a {
  color: #4CAF50;
  text-decoration: none;
}

p a:hover {
  text-decoration: underline;
}
</style>
